package com.tuanzi.loan.web.bean.application;

import com.base.common.util.CollectionUtils;
import com.google.common.collect.Lists;
import com.starbaba.model.bean.BadgeInfo;
import com.tuanzi.loan.business.entity.application.LoanApplicationExport;
import com.tuanzi.loan.business.entity.application.LoanApplicationExportGroup;
import com.tuanzi.loan.business.entity.application.LoanApplicationExportGroupPage;
import com.tuanzi.loan.business.entity.common.CommProductChannel;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.application.LoanApplicationExportGroupPageService;
import com.tuanzi.loan.business.service.application.LoanApplicationExportGroupService;
import com.tuanzi.loan.business.service.application.LoanApplicationExportService;
import com.tuanzi.loan.business.service.common.CommProductIdService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.application.Action;
import com.tuanzi.loan.vo.view.application.Badge;
import com.tuanzi.loan.vo.view.application.ExportReplaceCondition;
import com.tuanzi.loan.vo.view.family.product.LoanApplicationExportView;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.TabChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @Auther: hequnayu
 * @Date: 2019/7/31 15:15
 * @Description:
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanApplicationExportInfoBean extends JSFInfoBean<LoanApplicationExportView> {

    @Autowired
    private LoanApplicationExportService exportService;
    @Autowired
    private LoanApplicationExportGroupService groupService;
    @Autowired
    private LoanApplicationExportGroupPageService pageService;
    @Autowired
    private CommProductIdService commProductIdService;

    private List<SelectItem> exportGroup;
    private List<CommProductId> allCommProductIds;
    private List<SortCommProduct> sortCommProductIds;
    private List<CommProductChannel> commProductChannels;
    private List<LoanApplicationExport> replaceExportList;
    private String parentProd;
    private final Integer BANNER_REPLACE_GROUPID = 27;
    private final Integer ICON_REPLACE_GROUPID = 28;
    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = exportService.loadApplicationExportView(NumberUtils.toLong(id));
        } else {
            $ = new LoanApplicationExportView();
            changeStatusToAdd();
        }
        commProductChannels = super.getCommProductChannels();
        initExportGroup();
        initCommProducts();
        initInteractionAndOtherInfo();
        onSelectExportGroup();
    }

    public void onSave() {
        if (null != $.getSelectedProducts()){
            $.getSelectedProducts().clear();
        }else{
            $.setSelectedProducts(new ArrayList<>());
        }
        for (SortCommProduct sortCommProduct : sortCommProductIds){
            $.getSelectedProducts().addAll(sortCommProduct.getSelectList());
        }
        if (!checkParams()){
            return ;
        }
        exportService.saveOrUpdateApplicationExport($);
        changeStatusToView();
        addSuccessfullyMessage();
    }

    public void onCopyApplication() {
        $.setId(null);
        $.setStatus(0);
        changeStatusToEdit();
    }

    public void initExportGroup(){
        exportGroup = Lists.newArrayList();
        List<LoanApplicationExportGroupPage> pages = pageService.findAll();
        pages.stream().forEach((x) -> {
            SelectItemGroup group = new SelectItemGroup(x.getName());
            List<LoanApplicationExportGroup> pageGroup = groupService.findByPageId(x.getId());
            group.setSelectItems(pageGroup.stream().map(g -> new SelectItem(g.getId(),g.getName())).toArray(SelectItem[]::new));
            exportGroup.add(group);
        });
    }

    public void onSelectExportGroup(){
        if ($.getExportGroupId() == null){
            return;
        }
        LoanApplicationExportGroup exportGroup = groupService.findOne($.getExportGroupId());
        if (0 == exportGroup.getType()){
            replaceExportList = exportService.findByGroupId(BANNER_REPLACE_GROUPID);
        }else if(1 == exportGroup.getType()){
            replaceExportList = exportService.findByGroupId(ICON_REPLACE_GROUPID);
        }

        if (CollectionUtils.isNotEmpty(replaceExportList) && $.getId() != null){
            replaceExportList = replaceExportList.stream().filter(r -> r.getId() != $.getId()).collect(Collectors.toList());
        }
    }

    private void initInteractionAndOtherInfo() {
        if (null == $.getAction()) {
            Action.LaunchParams launchParams = new Action.LaunchParams();
            $.setAction(new Action());
            $.getAction().setLaunchParams(launchParams);
        }

        if (null == $.getBadge()) {
            $.setBadge(new BadgeInfo());
            $.getBadge().setLocation(3);
            $.getBadge().setTimestamp(System.currentTimeMillis());
        }

        if (null == $.getExportReplaceCondition()) {
            $.setExportReplaceCondition(new ExportReplaceCondition());
        }
    }

    public void initCommProducts(){
        allCommProductIds = commProductIdService.findAll().stream().filter(x -> x.getRealPrdid() != null && x.getIsApp().equals(1)).collect(Collectors.toList());
        sortCommProductIds = new ArrayList<>();
        List<Dictionary> large_common_product = super.dictionaryService.findAllByCode("LARGE_COMMON_PRODUCT");
        for (Dictionary dic : large_common_product){
            SortCommProduct sortCommProduct = new SortCommProduct();
            sortCommProduct.setName(dic.getName());
            sortCommProduct.setList(allCommProductIds.stream().filter(p -> {
                return p.getParentId().equals(dic.getValue1()) ;
            }).collect(Collectors.toList()));
            if (!CollectionUtils.isEmpty(sortCommProduct.getList())){
                List<String> stringList = sortCommProduct.getList().stream().map(p -> p.getProductId().toString()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty($.getSelectedProducts())){
                    sortCommProduct.setSelectList(stringList.stream().filter(s -> $.getSelectedProducts().contains(s)).collect(Collectors.toList()));
                }
                sortCommProductIds.add(sortCommProduct);
            }
        }
    }

    public void onUploadImgBefore(FileUploadEvent event) {
        $.setImgurl(uploadImg(event.getFile()));
    }

    public void onUploadImgAfter(FileUploadEvent event) {
        $.setAfClickImgurl(uploadImg(event.getFile()));
    }

    public void onSelectAllProduct() {
        if ($.getSelectedProducts() == null) {
            $.setSelectedProducts(new ArrayList<>());
        }
        if ($.getSelectedProducts().size() < allCommProductIds.size()) {
            for (SortCommProduct sortCommProduct : sortCommProductIds){
                sortCommProduct.setSelectList(sortCommProduct.getList().stream().map(product -> product.getProductId().toString()).collect(Collectors.toList()));
                $.getSelectedProducts().addAll(sortCommProduct.getSelectList());
            }
        }else{
            for (SortCommProduct sortCommProduct : sortCommProductIds){
                sortCommProduct.getSelectList().clear();
            }
            $.getSelectedProducts().clear();
        }
    }

    public void onSelectSortAllProduct(int index){
        SortCommProduct sortCommProduct = sortCommProductIds.get(index);
        if (sortCommProduct.getSelectList().size() < sortCommProduct.getList().size()){
            sortCommProduct.setSelectList(sortCommProduct.getList().stream().map(product -> product.getProductId().toString()).collect(Collectors.toList()));
        }else{
            sortCommProduct.getSelectList().clear();
        }

    }

    public void onSelectAllExcludeChannel() {
        if ($.getSelectedExcludeChannels() == null)
            $.setSelectedExcludeChannels( new ArrayList<>());
        if ($.getSelectedExcludeChannels().size() < commProductChannels.size()) {
            $.setSelectedExcludeChannels(commProductChannels.stream().map(channel -> channel.getChannelCode().toString()).collect(Collectors.toList()));
        } else {
            $.getSelectedExcludeChannels().clear();
        }
    }

    private int updateCount = 0;
    public void onChangeTab(TabChangeEvent event) {
        if (0 == updateCount && "交互信息".equals(event.getTab().getTitle())) {
            updateCount++;
            update("applicationForm:applicationTabView:interactionDetail");
//            update("applicationForm:applicationTabView:mustLogin");
        }
    }

    public String onReturn(String url) {
        return redirect(url, getParam());
    }

    public boolean checkParams(){
        if(StringUtils.isBlank($.getTitle())){
            addErrorMessage("标题不能为空");
            return false;
        }
        if(CollectionUtils.isEmpty($.getSelectedPlatforms())){
            addErrorMessage("平台不能为空");
            return false;
        }
        if(null == $.getExportGroupId()){
            addErrorMessage("所属组不能为空");
            return false;
        }
        if(null == $.getPosition()){
            addErrorMessage("位置不能为空");
            return false;
        }
        if(null == $.getStatus()){
            addErrorMessage("是否上线不能为空");
            return false;
        }
        if ($.getMinVersionCode() != null && $.getMaxVersionCode() != null){
            if ($.getMaxVersionCode() < $.getMinVersionCode()){
                addErrorMessage("最大版本号不能小于最小版本号");
                return false;
            }
        }
        if ($.getStartTime() != null && $.getEndTime() != null){
            if ($.getEndTime().getTime() < $.getStartTime().getTime()){
                addErrorMessage("在线结束时间不能早于在线开始时间");
                return false;
            }
        }
        if(StringUtils.isBlank($.getImgurl())){
            addErrorMessage("图片（点击前）不能为空");
            return false;
        }
        if(CollectionUtils.isEmpty($.getSelectedProducts())){
            addErrorMessage("上线产品不能为空");
            return false;
        }
        if(StringUtils.isBlank($.getLaunch())){
            addErrorMessage("跳转类型不能为空");
            return false;
        }
        return true;
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(EXPORT_TYPE, PLATFORM ,EXPORT_ACTION_TYPE,EXPORT_USER_TYPE,EXPORT_BADGE_STATUS,EXPORT_BADGE_RESIDENT,EXPORT_REPLACE_CONDITION,LARGE_COMMON_PRODUCT);
    }

    @Data
    public class SortCommProduct{
        private String name;
        private List<CommProductId> list;
        private List<String> selectList;
    }
}
